package com.customization.unionpay.market.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudstore.dev.api.bean.MessageBean;
import com.cloudstore.dev.api.bean.MessageType;
import com.cloudstore.dev.api.util.Util_Message;
import com.customization.unionpay.market.service.impl.ClearingRefundServiceImpl;
import com.engine.cube.biz.ShardingActionHelper;
import com.weaver.formmodel.util.DateHelper;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.formmode.data.ModeDataIDUpdateSingle;
import weaver.formmode.setup.ModeRightInfo;
import weaver.formmode.webservices.FileUtil;
import weaver.formmode.webservices.exception.ModeDataExceptionEnum;
import weaver.formmode.webservices.exception.ModeDataServiceException;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.soa.workflow.request.*;
import weaver.workflow.webservices.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author sjm
 * @description 表单数据工具类
 */
public class FormDataUtils {

    private static final Logger log = LoggerFactory.getLogger(FormDataUtils.class);
    private static ModeDataIDUpdateSingle modeDataIDUpdateSingle = ModeDataIDUpdateSingle.INSTANCE;

    /**
     * 获取主表数据库表名
     *
     * @param formid
     * @return
     */
    public static String getTableName(int formid) {
        RecordSet rs = new RecordSet();
        String maintablename = "";
        String sql = "select tablename from workflow_bill where id = ? ";
        rs.executeQuery(sql, formid);
        while (rs.next()) {
            maintablename = Util.null2String(rs.getString("tablename"));
        }
        return maintablename;
    }

    /**
     * 获取流程主表数据库表名
     *
     * @param workflowid
     * @return
     */
    public static String getWorkFlowTableName(String workflowid) {
        RecordSet rs = new RecordSet();
        String maintablename = "";
        String sql = "select wb.tablename as tablename from workflow_base wr join workflow_bill wb on wb.id = wr.formid where wr.id = ? ";
        rs.executeQuery(sql, workflowid);
        while (rs.next()) {
            maintablename = Util.null2String(rs.getString("tablename"));
        }
        return maintablename;
    }

    /**
     * 获取流程明细表数据库表名
     *
     * @param flowId
     * @return
     */
    public static String getWorkFlowTableDetailsName(String flowId) {
        RecordSet rs = new RecordSet();
        String maintablename = "";
        String sql = "select tablename from workflow_billdetailtable where billid = ? ";
        rs.executeQuery(sql, flowId);
        while (rs.next()) {
            if ("".equals(maintablename)) {
                maintablename += Util.null2String(rs.getString("tablename"));
            } else {
                maintablename += "," + Util.null2String(rs.getString("tablename"));
            }
        }
        return maintablename;
    }

    /**
     * 获取formid通过流程表单id
     *
     * @param workflowid
     * @return
     */
    public static String getFormIdByWorkFlowId(String workflowid) {
        RecordSet rs = new RecordSet();
        String formid = "";
        String sql = "select formid from workflow_base where id=? ";
        rs.executeQuery(sql, workflowid);
        while (rs.next()) {
            formid = Util.null2String(rs.getString("formid"));
        }
        return formid;
    }

    /**
     * 创建一条空数据，获取数据id
     *
     * @param billtablename
     * @param formmodeid
     * @param userid
     * @param usertype
     * @return
     */
    public static int getBillId(String billtablename, int formmodeid, int userid, int usertype) {
        int billid = -1;

        String currentdate = DateHelper.getCurrentDate();

        String currenttime = DateHelper.getCurrentTime();
        //取数据库服务器的当前时间
        RecordSet rs = new RecordSet();
        rs.executeProc("GetDBDateAndTime", "");
        if (rs.next()) {
            currentdate = rs.getString("dbdate");
            currenttime = rs.getString("dbtime");
        }
        billid = modeDataIDUpdateSingle.getModeDataNewIdByUUID(billtablename, formmodeid, userid, usertype, currentdate, currenttime);
        return billid;
    }

    /**
     * 获取流程信息
     *
     * @param requestid
     * @return
     */
    public static JSONObject getWorkFlowInfo(String requestid) {
        RecordSet rst = new RecordSet();

        JSONObject workFlowInfo = new JSONObject();
        //获取流程基础信息
        String sqls = " select wr.requestname, wr.workflowid, wb.formid, wr.creater, wr.createdate, wr.createtime from workflow_requestbase wr ,workflow_base wb where  requestid=? and wr.workflowid = wb.id ";
        rst.executeQuery(sqls, requestid);
        if (rst.next()) {
            workFlowInfo.put("requestName", rst.getString("requestname"));
            workFlowInfo.put("workflowId", rst.getString("workflowid"));
            workFlowInfo.put("formId", rst.getString("formid"));
            workFlowInfo.put("creater", rst.getString("creater"));
            workFlowInfo.put("createDate", rst.getString("createdate"));
            workFlowInfo.put("createTime", rst.getString("createtime"));
            return workFlowInfo;
        } else {
            return null;
        }
    }

    /**
     * 获取流程表单数据
     *
     * @param requestInfo
     * @return
     */
    public static Map<String, Object> getAllFormData(RequestInfo requestInfo) {
        Map<String, Object> hashMap = new HashMap<>();

        Map<String, String> mainMap = new HashMap<>();//主字段的值
        Map<String, Map<String, Map<String, String>>> detailMap = new HashMap<>();//所有明细表的值

        try {

            Property[] properties = requestInfo.getMainTableInfo().getProperty();// 获取表单主字段信息

            for (int i = 0; i < properties.length; i++) {// 主表数据
                String name = properties[i].getName().toLowerCase();
                String value = properties[i].getValue();
                mainMap.put(name, Util.null2String(value));
            }

            DetailTable[] detailtable = requestInfo.getDetailTableInfo().getDetailTable();// 获取明细表
            if (detailtable.length > 0) {
                // 遍历明细表
                for (int i = 1; i <= detailtable.length; i++) {
                    Map<String, Map<String, String>> rowList = new LinkedHashMap<>();
                    DetailTable dt = detailtable[i - 1];
                    Row[] s = dt.getRow();

                    for (int j = 1; j <= s.length; j++) {
                        Map<String, String> rowMap = new LinkedHashMap<>();
                        Row r = s[j - 1];

                        Cell[] c = r.getCell();
                        for (int k = 0; k < c.length; k++) {
                            Cell c1 = c[k];
                            String name = c1.getName().toLowerCase();
                            String value = c1.getValue();

                            rowMap.put(name, Util.null2String(value));
                        }
                        if (rowMap.size() > 0) {
                            rowList.put(r.getId(), rowMap);
                        }

                    }
                    detailMap.put(dt.getTableDBName().substring(dt.getTableDBName().lastIndexOf("_") + 1), rowList);
                }
            }
            hashMap.put("mainMap", mainMap);
            hashMap.put("detailMap", detailMap);
            return hashMap;
        } catch (Exception e) {
            log.error("解析流程数据异常：" + e.getMessage());
            return null;
        }
    }

    /**
     * 获取选中建模数据数据（只有主表）
     *
     * @param requestInfo
     * @return
     */
    public static List<JSONObject> getChooseFormData(RequestInfo requestInfo) {
        List<JSONObject> list = new ArrayList<>();
        try {

            Property[] properties = requestInfo.getMainTableInfo().getProperty();// 获取表单主字段信息

            JSONObject json = new JSONObject();
            for (int i = 0; i < properties.length; i++) {// 主表数据
                String name = properties[i].getName().toLowerCase();
                String value = properties[i].getValue();
                json.put(name, Util.null2String(value));
            }
            list.add(json);

            return list;
        } catch (Exception e) {
            log.error("解析流程数据异常：" + e.getMessage());
            return null;
        }
    }

    /**
     * 获取选中建模主表数据
     */
    public static Map<String, Object> getMainFormData(RequestInfo requestInfo) {
        Map<String, Object> result = new HashMap<>();
        try {
            Property[] properties = requestInfo.getMainTableInfo().getProperty();
            for (int i = 0; i < properties.length; i++) {// 主表数据
                String name = properties[i].getName().toLowerCase();
                String value = properties[i].getValue();
                result.put(name, Util.null2String(value));
            }
            return result;
        } catch (Exception e) {
            log.error("解析流程数据异常：" + e.getMessage());
            return null;
        }
    }

    /**
     * 获取某一张明细表的数据
     *
     * @param index
     * @param requestInfo
     * @return
     */
    public static List<Map<String, Object>> getDetailFormDataByIndex(int index, RequestInfo requestInfo) {
        try {
            List<Map<String, Object>> result = new ArrayList<>();
            DetailTable detailTable = requestInfo.getDetailTableInfo().getDetailTable(index);
            if (detailTable != null) {
                if (detailTable.getRow() != null && detailTable.getRow().length > 0) {
                    for (Row row : detailTable.getRow()) {
                        Map<String, Object> map = new HashMap<>();
                        for (Cell cell : row.getCell()) {
                            map.put(cell.getName(), cell.getValue());
                        }
                        result.add(map);
                    }
                }
            }
            return result;
        } catch (Exception e) {
            log.error("获取明细表数据异常" + e.getMessage());
            return null;
        }
    }

    /**
     * 获取枚举相关信息
     *
     * @param formid
     * @param fieldName
     * @param selectName
     * @return
     */
    public static List<JSONObject> getItemInfo(int formid, String fieldName, String selectName, String selectValue) {

        RecordSet rst = new RecordSet();
        List<JSONObject> resultJsons = new ArrayList<>();
        try {
            //获取流程基础信息
            StringBuilder sqls = new StringBuilder(" select ws.selectname as name ,ws.selectvalue as value ,ws.fieldid as fieldId from workflow_billfield b " +
                    " JOIN workflow_SelectItem ws ON ws.fieldid = b.id " +
                    " where b.fieldhtmltype = 5  and  b.billid = ");
            sqls.append(formid);
            if (StrUtil.isNotBlank(fieldName)) {
                sqls.append(" and b.fieldname = '");
                sqls.append(fieldName);
                sqls.append("' ");
            }
            if (StrUtil.isNotBlank(selectName)) {
                sqls.append(" and ws.selectname='");
                sqls.append(selectName);
                sqls.append("' ");
            }
            if (StrUtil.isNotBlank(selectValue)) {
                sqls.append(" and ws.selectvalue='");
                sqls.append(selectValue);
                sqls.append("' ");
            }
            log.info("sqls:" + sqls.toString());
            rst.executeQuery(sqls.toString());
            while (rst.next()) {
                JSONObject itemInfo = new JSONObject();
                itemInfo.put("fieldId", Util.null2String(rst.getString("fieldId")));
                itemInfo.put("name", Util.null2String(rst.getString("name")));
                itemInfo.put("value", Util.null2String(rst.getString("value")));
                resultJsons.add(itemInfo);
            }
        } catch (Exception e) {
            log.error("获取枚举数据异常：" + e.getMessage());
        }
        return resultJsons;
    }

    /**
     * 获取枚举值下标
     *
     * @param formid
     * @param fieldName
     * @param selectName
     * @return
     */
    public static String getItemValue(int formid, String fieldName, String selectName) {
        List<JSONObject> itemInfo = getItemInfo(formid, fieldName, selectName, null);
        if (itemInfo.size() > 0) {
            return itemInfo.get(0).getString("value");
        } else {
            log.error("获取枚举value异常!");
        }
        return null;
    }

    /**
     * 获取枚举值显示值
     *
     * @param formid
     * @param fieldName
     * @param selectValue
     * @return
     */
    public static String getItemName(int formid, String fieldName, String selectValue) {
        List<JSONObject> itemInfo = getItemInfo(formid, fieldName, null, selectValue);
        if (itemInfo.size() > 0) {
            return itemInfo.get(0).getString("name");
        } else {
            log.error("获取枚举name异常!");
        }
        return null;
    }

    /**
     * 获取HttpServletRequest中请求体
     *
     * @param req
     * @return
     * @throws IOException
     */
    public static String readBody(HttpServletRequest req) throws IOException {
        if ("POST".equals(req.getMethod())) {
            StringBuilder result = new StringBuilder();
            BufferedReader br = req.getReader();
            String line;
            while ((line = br.readLine()) != null) {
                result.append(line);
            }
            br.close();
            return result.toString();
        }
        return null;
    }

    /**
     * 获取HttpServletRequest中请求体
     * @param request
     * @return
     * @throws IOException
     */
    public static String readBodyUTF8(HttpServletRequest request) {
        if ("POST".equals(request.getMethod())) {
            InputStream is = null;
            try {
                is = request.getInputStream();
                StringBuilder sb = new StringBuilder();
                byte[] b = new byte[4096];
                for (int n; (n = is.read(b)) != -1; ) {
                    sb.append(new String(b, 0, n, "utf-8"));
                }
                return sb.toString();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (null != is) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

    /**
     * JSONArray转中间用逗号隔开的字符串  ["1","2","3"]转成"1,2,3"
     *
     * @param jsonArray
     * @return
     */
    public static String jsonArrayToStr(JSONArray jsonArray) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < jsonArray.size(); i++) {
            try {
                if (i > 0) {
                    result.append(",");
                }
                result.append(jsonArray.getString(i));
            } catch (Exception e) {
                e.printStackTrace();
                log.error("获取id异常：" + e.getMessage());
            }
        }
        return result.toString();
    }

    /**
     * 在线文件添加到表单，并存入数据库
     *
     * @param modeid
     * @param userid
     * @param billid
     * @param tablename
     * @param files_List
     */
    public static void resolveFilesElement(int modeid, int userid, int billid, String tablename, List<JSONObject> files_List, String filedname) throws Exception {
        FileUtil fileutil = new FileUtil();
        if (null != files_List) {
            String filename = "";
            String filecontent = "";
            String sql = "";
            String docids = "";
            RecordSet rs = new RecordSet();
            for (int i = 0; i < files_List.size(); i++) {
                filename = files_List.get(i).getString("filename");
                filecontent = files_List.get(i).getString("filecontent");
                if (!"".equals(filename) && !"".equals(filecontent)) {
                    if (!"".equals(docids)) {
                        docids += ",";
                    }
                    int retDocID = fileutil.buildFile(modeid, userid, filecontent, filename);
                    if (retDocID == 0) {
                        throw new ModeDataServiceException(ModeDataExceptionEnum.URLGET_DOCID_ZERO.toString());
                    }
                    docids += retDocID;
                }
            }
            sql = "update " + tablename + " set " + filedname + "='" + docids + "' where id=?";
            rs.executeUpdate(sql, billid);
        }
    }

    /**
     * 根据长度切分数组
     *
     * @param list
     * @param maxSubListSize
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> splitList(List<T> list, int maxSubListSize) {
        List<List<T>> result = new ArrayList<>();
        int totalSize = list.size();

        for (int i = 0; i < totalSize; i += maxSubListSize) {
            int end = Math.min(totalSize, i + maxSubListSize);
            result.add(new ArrayList<>(list.subList(i, end)));
        }

        return result;
    }

    /**
     * 发起流程
     *
     * @param user       发起用户
     * @param json       整体数据
     * @param mainSize   主表字段个数
     * @param sonSize    明细表个数
     * @param workflowId 流程id
     * @param isNext     是否需要发起
     * @param level      紧急等级       // 0 正常 1 重要 2 紧急
     * @param title      流程标题       // 0 否， 1 是
     * @return
     */
    public static synchronized String createWorkFlow(User user, JSONObject json, int mainSize, int sonSize, String workflowId, String isNext, String level, String title) {

        WorkflowRequestTableField[] wrti = new WorkflowRequestTableField[mainSize];
        WorkflowDetailTableInfo[] WorkflowDetailTableInfo = null;
        if(sonSize > 0) {
            WorkflowDetailTableInfo = new WorkflowDetailTableInfo[sonSize];
        }

        int mainIndex = 0;
        int sonListIndex = 0;
        for (Object mainKey : json.keySet()) {
            String mainKeyStr = mainKey.toString();
            Object mainValue = json.get(mainKeyStr);
            if (mainValue instanceof List) {
                // 明细表集合
                JSONArray sonData = json.getJSONArray(mainKeyStr);
                int singleSonSize = sonData.size();
                if(singleSonSize > 0) {
                    //添加明细条数
                    WorkflowRequestTableRecord[] wrtri = new WorkflowRequestTableRecord[singleSonSize + 1];

                    // 遍历明细集合
                    for (int i = 0; i < singleSonSize; i++) {
                        // 单条明细数据
                        JSONObject sonSingleEL = sonData.getJSONObject(i);
                        int size = sonSingleEL.size();
                        // 明细字段个数
                        WorkflowRequestTableField[] wrtiSon = new WorkflowRequestTableField[size];
                        int sonIndex = 0;
                        for (Object sonSingleELKey : sonSingleEL.keySet()) {
                            String sonSingleELKeyStr = sonSingleELKey.toString();
                            JSONObject sonSingleELJson = sonSingleEL.getJSONObject(sonSingleELKeyStr);
                            wrtiSon[sonIndex] = new WorkflowRequestTableField();
                            String type = sonSingleELJson.getString("type");
                            String name = sonSingleELJson.getString("name");
                            if ("file".equals(type)) {
                                JSONArray value = sonSingleELJson.getJSONArray("value");
                                if (value.size() == 1) {
                                    JSONObject jsonObject = value.getJSONObject(0);
                                    wrtiSon[sonIndex].setFieldName(name);
                                    wrtiSon[sonIndex].setFieldValue(jsonObject.getString("value"));
                                    wrtiSon[sonIndex].setFieldType(jsonObject.getString("type"));
                                }
                                if (value.size() > 1) {
                                    String finalType = "";
                                    String finalValue = "";
                                    for (int k = 0; k < value.size(); k++) {
                                        finalType += value.getJSONObject(k).getString("type");
                                        finalValue += value.getJSONObject(k).getString("value");
                                        if (k > 0) {
                                            finalType += "|" + value.getJSONObject(k).getString("type");
                                            finalValue += "|" + value.getJSONObject(k).getString("value");
                                        }
                                    }
                                    wrtiSon[sonIndex].setFieldName(name);
                                    wrtiSon[sonIndex].setFieldValue(finalValue);
                                    wrtiSon[sonIndex].setFieldType(finalType);
                                }
                            } else {
                                String value = sonSingleELJson.getString("value");
                                wrtiSon[sonIndex].setFieldName(name);
                                wrtiSon[sonIndex].setFieldValue(value);
                            }
                            wrtiSon[sonIndex].setView(true);
                            wrtiSon[sonIndex].setEdit(true);
                            sonIndex++;
                        }
                        wrtri[i] = new WorkflowRequestTableRecord();
                        wrtri[i].setWorkflowRequestTableFields(wrtiSon);
                    }
                    WorkflowDetailTableInfo[sonListIndex] = new WorkflowDetailTableInfo();
                    WorkflowDetailTableInfo[sonListIndex].setWorkflowRequestTableRecords(wrtri);
                    sonListIndex++;
                }
            } else {
                // 主表字段
                JSONObject singleEL = json.getJSONObject(mainKeyStr);
                wrti[mainIndex] = new WorkflowRequestTableField();
                String type = singleEL.getString("type");
                String name = singleEL.getString("name");
                if ("file".equals(type)) {
                    JSONArray value = singleEL.getJSONArray("value");
                    if (value.size() == 1) {
                        JSONObject jsonObject = value.getJSONObject(0);
                        wrti[mainIndex].setFieldName(name);
                        wrti[mainIndex].setFieldValue(jsonObject.getString("value"));
                        wrti[mainIndex].setFieldType(jsonObject.getString("type"));
                    }
                    if (value.size() > 1) {
                        String finalType = "";
                        String finalValue = "";
                        for (int k = 0; k < value.size(); k++) {
                            finalType += value.getJSONObject(k).getString("type");
                            finalValue += value.getJSONObject(k).getString("value");
                            if (k > 0) {
                                finalType += "|" + value.getJSONObject(k).getString("type");
                                finalValue += "|" + value.getJSONObject(k).getString("value");
                            }
                        }
                        wrti[mainIndex].setFieldName(name);
                        wrti[mainIndex].setFieldValue(finalValue);
                        wrti[mainIndex].setFieldType(finalType);
                    }
                } else {
                    String value = singleEL.getString("value");
                    wrti[mainIndex].setFieldName(name);
                    wrti[mainIndex].setFieldValue(value);
                }
                wrti[mainIndex].setView(true);
                wrti[mainIndex].setEdit(true);
                mainIndex++;
            }
        }

        WorkflowRequestTableRecord[] wrtri = new WorkflowRequestTableRecord[1];
        wrtri[0] = new WorkflowRequestTableRecord();
        wrtri[0].setWorkflowRequestTableFields(wrti);

        WorkflowMainTableInfo wmi = new WorkflowMainTableInfo();
        wmi.setRequestRecords(wrtri);

        //添加工作流id
        WorkflowBaseInfo wbi = new WorkflowBaseInfo();
        wbi.setWorkflowId(workflowId);

        WorkflowRequestInfo wri = new WorkflowRequestInfo();
        wri.setCreatorId(user.getUID() + "");
        wri.setRequestLevel(level);
        wri.setIsnextflow(isNext);

        wri.setRequestName(title);
        wri.setWorkflowMainTableInfo(wmi);
        if(sonSize > 0) {
            wri.setWorkflowDetailTableInfos(WorkflowDetailTableInfo);
        }
        wri.setWorkflowBaseInfo(wbi);
        log.info("wri:"+wri);

        WorkflowServiceImpl WorkflowServicePortTypeProxy = new WorkflowServiceImpl();
        return WorkflowServicePortTypeProxy.doCreateWorkflowRequest(wri, user.getUID());
    }

    /**
     * 回退流程
     *
     * @param requestid
     * @param userid
     */
    public static void rejectRequest(int requestid, int userid) {
        WorkflowServiceImpl WorkflowServicePortTypeProxy = new WorkflowServiceImpl();
        WorkflowRequestInfo WorkflowRequestInfo = WorkflowServicePortTypeProxy.getWorkflowRequest(requestid, userid, 0);
        String str = WorkflowServicePortTypeProxy.submitWorkflowRequest(WorkflowRequestInfo, requestid, userid, "reject", "退回流程" + new Date());
        log.info(str);
    }

    /**
     * 活动码生成日期 取“营销平台活动授权码”前8位数字
     *
     * @param numberCode
     * @return
     */
    public static String getDateStrByCode(String numberCode) {
        // 提取前8位数字
        String digits = numberCode.substring(0, 8);

        // 将数字转换为日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate date = LocalDate.parse(digits, formatter);

        // 格式化成所需的日期字符串格式
        return date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }

    /**
     * 根据部门唯一值获取部门id
     *
     * @param code
     * @return
     */
    public static String getIdByDepartmentCode(String code) {
        RecordSet rs = new RecordSet();
        String id = "";
        String sql = "select id from hrmdepartment where outkey=? ";
        rs.executeQuery(sql, code);
        while (rs.next()) {
            id = Util.null2String(rs.getString("id"));
        }
        return id;
    }

    /**
     * 根据部门唯一值获取部门信息
     *
     * @param code
     * @return
     */
    public static JSONObject getInfoByDepartmentCode(String code) {
        RecordSet rs = new RecordSet();
        JSONObject info = null;
        String sql = "select id,subcompanyid1 from hrmdepartment where outkey=? ";
        rs.executeQuery(sql, code);
        while (rs.next()) {
            info = new JSONObject();
            info.put("id", Util.null2String(rs.getString("id")));
            info.put("subCompanyId", Util.null2String(rs.getString("subcompanyid1")));
        }
        return info;
    }

    /**
     * 根据人员唯一值获取人员id
     *
     * @param code
     * @return
     */
    public static String getIdByResourceCode(String code) {
        RecordSet rs = new RecordSet();
        String id = "";
        String sql = "select id from hrmresource where outkey=? ";
        rs.executeQuery(sql, code);
        while (rs.next()) {
            id = Util.null2String(rs.getString("id"));
        }
        return id;
    }

    /**
     * 根据人员唯一值获取人员信息
     *
     * @param code
     * @return
     */
    public static JSONObject getUserInfoByResourceCode(String code) {
        RecordSet rs = new RecordSet();
        JSONObject info = null;
        String sql = "select id,lastname from hrmresource where outkey=? ";
        rs.executeQuery(sql, code);
        while (rs.next()) {
            info = new JSONObject();
            info.put("id", Util.null2String(rs.getString("id")));
            info.put("name", Util.null2String(rs.getString("lastname")));
        }
        return info;
    }

    /**
     * 根据人员登录名获取人员信息
     *
     * @param code
     * @return
     */
    public static JSONObject getUserInfoByResourceLoginId(String code) {
        RecordSet rs = new RecordSet();
        JSONObject info = null;
        String sql = "select id,lastname from hrmresource where loginid=? ";
        log.info("sql:"+sql);
        rs.executeQuery(sql, code);
        while (rs.next()) {
            info = new JSONObject();
            info.put("id", Util.null2String(rs.getString("id")));
            info.put("name", Util.null2String(rs.getString("lastname")));
        }
        return info;
    }

    /**
     * 根据人员登录名获取人员id
     *
     * @param code
     * @return
     */
    public static String getIdByResourceLoginId(String code) {
        RecordSet rs = new RecordSet();
        String id = "";
        String sql = "select id from hrmresource where loginid=? ";
        log.info("sql:"+sql);
        rs.executeQuery(sql, code);
        while (rs.next()) {
            id = Util.null2String(rs.getString("id"));
        }
        return id;
    }

    /**
     * 根据人员登录名获取人员outkey
     *
     * @param code
     * @return
     */
    public static String getResourceCodeByResourceLoginId(String code) {
        RecordSet rs = new RecordSet();
        String outkey = "";
        String sql = "select outkey from hrmresource where loginid=? ";
        log.info("sql:"+sql);
        rs.executeQuery(sql, code);
        while (rs.next()) {
            outkey = Util.null2String(rs.getString("outkey"));
        }
        return outkey;
    }

    /**
     * 根据公司唯一值获取公司id
     *
     * @param code
     * @return
     */
    public static String getIdByCompanyCode(String code) {
        RecordSet rs = new RecordSet();
        String id = "";
        String sql = "select id from hrmsubcompany where outkey=? ";
        rs.executeQuery(sql, code);
        while (rs.next()) {
            id = Util.null2String(rs.getString("id"));
        }
        return id;
    }

    public static Boolean isCompanyOrDepartment(String code){
        boolean isCompany = true;
        String id = getIdByCompanyCode(code);
        log.info("id:"+id);
        if(id == null || "".equals(id)){
            isCompany = false;
        }
        return isCompany;
    }

    /**
     * 根据人员id获取人员唯一值
     *
     * @param code
     * @return
     */
    public static String getResourceCodeById(String code) {
        RecordSet rs = new RecordSet();
        String outkey = "";
        String sql = "select outkey from hrmresource where id=? ";
        rs.executeQuery(sql, code);
        while (rs.next()) {
            outkey = Util.null2String(rs.getString("outkey"));
        }
        return outkey;
    }

    /**
     * 根据人员名称获取人员id
     *
     * @param name
     * @return
     */
    public static String getResourceIdByName(String name) {
        RecordSet rs = new RecordSet();
        String id = "";
        String sql = "select id from hrmresource where lastname='"+name+"' ";
        rs.executeQuery(sql);
        while (rs.next()) {
            id = Util.null2String(rs.getString("id"));
        }
        return id;
    }

    /**
     * 根据部门id获取部门唯一值
     *
     * @param code
     * @return
     */
    public static String getDepartmentCodeById(String code) {
        RecordSet rs = new RecordSet();
        String outkey = "";
        String sql = "select outkey from hrmdepartment where id=? ";
        rs.executeQuery(sql, code);
        while (rs.next()) {
            outkey = Util.null2String(rs.getString("outkey"));
        }
        return outkey;
    }

    /**
     * 根据公司id获取公司唯一值
     *
     * @param code
     * @return
     */
    public static String getCompanyCodeById(String code) {
        RecordSet rs = new RecordSet();
        String outkey = "";
        String sql = "select outkey from hrmsubcompany where id=? ";
        rs.executeQuery(sql, code);
        while (rs.next()) {
            outkey = Util.null2String(rs.getString("outkey"));
        }
        return outkey;
    }

    /**
     * 获取下载文件url的http
     *
     * @param furl
     * @return
     */
    public static String getPreTitle(String furl) {
        String[] split = furl.split(":");
        return split[0];
    }

    /**
     * 获取下载文件url的文件名
     *
     * @param furl
     * @return
     */
    public static String getTailTitle(String furl) {
        String[] split = furl.split("\\/");
        return split[split.length - 1];
    }

    /**
     * 六位小数万元转换两位元小数
     *
     * @param value
     * @return
     */
    public static String changeWanYuanToYuan(String value) {
        BigDecimal amountInYuan = new BigDecimal(value);
        BigDecimal amountInRenminbi = amountInYuan.multiply(new BigDecimal("10000")).setScale(2, BigDecimal.ROUND_HALF_UP);
        return amountInRenminbi.toString();
    }

    /**
     * 两位小数元转换六位小数万元
     *
     * @param value
     * @return
     */
    public static String changeYuanToWanYuan(String value) {
        BigDecimal originalValue = new BigDecimal(value);
        BigDecimal convertedValue = originalValue.divide(new BigDecimal("10000"), 6, BigDecimal.ROUND_HALF_UP);
        return convertedValue.toString();
    }

    /**
     * 日期字符串转日期
     *
     * @param format
     * @param dateString
     * @return
     */
    public static Date dateStringToDate(String format, String dateString) {
        Date date = null;

        // 定义日期字符串的格式
        SimpleDateFormat formatter = new SimpleDateFormat(format);

        try {
            // 解析日期字符串
            date = formatter.parse(dateString);
        } catch (ParseException e) {
            log.error("日期字符串转日期异常：" + e.getMessage());
        }
        return date;
    }


    /**
     * 改变日期字符串
     *
     * @param format
     * @param dateString
     * @param changeFormat
     * @return
     */
    public static String changeDateString(String format, String dateString, String changeFormat) {
        log.info("format："+format);
        log.info("dateString："+dateString);
        try {
            Date date = dateStringToDate(format, dateString);
            // 定义日期字符串的格式
            return new SimpleDateFormat(changeFormat).format(date);
        }catch (Exception e){
            log.info("改变日期字符串异常：" + e.getMessage());
            return "";
        }
    }

    /**
     * 获取经济事项信息 TODO 表名写死
     *
     * @param id
     * @return
     */
    public static JSONObject getEconomicMattersInfo(String id) {
        RecordSet rs = new RecordSet();
        JSONObject json = new JSONObject();
        String sql = "select bm,jjsx,sl from uf_jccs_jjsx where id=? ";
        log.info("sql：" + sql);
        rs.executeQuery(sql, id);
        while (rs.next()) {
            json.put("code", Util.null2String(rs.getString("bm")));
            json.put("name", Util.null2String(rs.getString("jjsx")));
            json.put("taxRate", Util.null2String(rs.getString("sl")));
        }
        log.info("json：" + json);
        return json;
    }

    /**
     * 获取经济事项信息 TODO 表名写死
     *
     * @param code
     * @return
     */
    public static JSONObject getEconomicMattersInfoByCode(String code) {
        RecordSet rs = new RecordSet();
        JSONObject json = new JSONObject();
        String sql = "select bm,jjsx,sl from uf_jccs_jjsx where bm=? ";
        log.info("sql：" + sql);
        rs.executeQuery(sql, code);
        while (rs.next()) {
            json.put("code", Util.null2String(rs.getString("bm")));
            json.put("name", Util.null2String(rs.getString("jjsx")));
            json.put("taxRate", Util.null2String(rs.getString("sl")));
        }
        log.info("json：" + json);
        return json;
    }

    /**
     * 获取预算项目信息 TODO 表名写死
     *
     * @param id
     * @return
     */
    public static JSONObject getProductInfo(String id) {
        RecordSet rs = new RecordSet();
        JSONObject json = new JSONObject();
        String sql = "select * from uf_ysxmdb where id=? ";
        rs.executeQuery(sql, id);
        while (rs.next()) {
            json.put("code", Util.null2String(rs.getString("xmbm")));
            json.put("name", Util.null2String(rs.getString("xmmc")));
        }
        return json;
    }

    /**
     * 获取合同信息 TODO 表名写死
     *
     * @param id
     * @return
     */
    public static JSONObject getContractInfo(String id) {
        RecordSet rs = new RecordSet();
        JSONObject json = new JSONObject();
        String sql = "select * from uf_zchttz where id=? ";
        rs.executeQuery(sql, id);
        while (rs.next()) {
            json.put("code", Util.null2String(rs.getString("htglbh")));
            json.put("name", Util.null2String(rs.getString("htmc")));
        }
        return json;
    }

    /**
     * 获取供应商信息 TODO 表名写死
     *
     * @param id
     * @return
     */
    public static JSONObject getGYSInfo(String id) {
        RecordSet rs = new RecordSet();
        JSONObject json = new JSONObject();
        String sql = "select * from uf_jccs_dgwldx where id=? ";
        rs.executeQuery(sql, id);
        while (rs.next()) {
            json.put("code", Util.null2String(rs.getString("wldxbm")));
            json.put("name", Util.null2String(rs.getString("wldxmc")));
        }
        return json;
    }

    /**
     * 转换数值保留两位小数
     *
     * @param valueStr
     * @return
     */
    public static String changeNumber(String valueStr) {
        try {
            // 创建 BigDecimal 对象
            BigDecimal value = new BigDecimal(valueStr);

            // 设置精度并保留两位小数，不使用四舍五入
            value = value.setScale(2, BigDecimal.ROUND_HALF_UP);

            return value.toString();
        } catch (Exception e) {
            log.error("转换数值异常：" + e.getMessage());

            return "0.00";
        }
    }

    /**
     * 修改错误信息
     *
     * @param errorInfo
     * @param tableName
     * @param requestId
     */
    public static void changeErrorInfo(String errorInfo, String tableName, String requestId) {
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);
        try {
            String updateSql = "update #{tableName} set htyy=?  where requestId = ? ";
            updateSql = updateSql.replace("#{tableName}", tableName);
            log.error("updateSql：" + updateSql+",htyy："+ errorInfo+",requestId："+ requestId);
            rst.executeUpdate(updateSql, errorInfo, requestId);
            // 提交事务
            rst.commit();
        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("修改错误信息：" + e.getMessage());
        }
    }

    /**
     * 修改授权码信息
     *
     * @param sqm
     * @param tableName
     * @param requestId
     */
    public static void changeSqmInfo(String sqm, String tableName, String requestId) {
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);
        try {
            String dateStrByCode = getDateStrByCode(sqm);
            String updateSql = "update #{tableName} set yxpthdsqm=?,hdmscrq=?  where requestId = ? ";
            updateSql = updateSql.replace("#{tableName}", tableName);
            rst.executeUpdate(updateSql, sqm, dateStrByCode, requestId);
            // 提交事务
            rst.commit();
        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("修改授权码信息异常：" + e.getMessage());
        }
    }

    /**
     * 获取申请单信息（会计引擎也相关）
     * @param yxptsxsqdh
     * @param yxptsxsqdh
     * @return
     */
    public static JSONObject getMarketingApplicationInfo(String yxptsxsqdh,String workFlowTableName) {
        RecordSet rst = new RecordSet();
        JSONObject workFlowInfo = null;
        //获取流程基础信息
        String sqls = " select main.yskzq yskzq, " +
                " main.PROJECT_CODE project_code, " +
                " main.zth zth," +
                " main.sfwdxy sfwdxy," +
                " main.sfwjdyw sfwjdyw, " +
                " detail.jjsx jjsx, " +
                " detail.yszrzx yszrzx, " +
                " detail.yskm yskm " +
                " from " +workFlowTableName+" main " +
                " join " +workFlowTableName+"_dt1 detail "+
                " on main.id = detail.mainid "+
                " where main.bdh='"+yxptsxsqdh+"' ";
        log.info("sqls:"+sqls);
        rst.executeQuery(sqls);
        while (rst.next()){
            workFlowInfo = new JSONObject();
            log.info("yskzq：" + rst.getString("yskzq"));
            workFlowInfo.put("yskzq", Util.null2String(rst.getString("yskzq")));
            log.info("project_code：" + rst.getString("project_code"));
            workFlowInfo.put("project_code", Util.null2String(rst.getString("project_code")));
            log.info("zth：" + rst.getString("zth"));
            workFlowInfo.put("zth", Util.null2String(rst.getString("zth")));
            log.info("sfwdxy：" + rst.getString("sfwdxy"));
            workFlowInfo.put("sfwdxy", Util.null2String(rst.getString("sfwdxy")));
            log.info("sfwjdyw：" + rst.getString("sfwjdyw"));
            workFlowInfo.put("sfwjdyw", Util.null2String(rst.getString("sfwjdyw")));
            log.info("jjsx：" + rst.getString("jjsx"));
            workFlowInfo.put("jjsx", Util.null2String(rst.getString("jjsx")));
            log.info("yszrzx：" + rst.getString("yszrzx"));
            workFlowInfo.put("yszrzx", Util.null2String(rst.getString("yszrzx")));
            log.info("yskm：" + rst.getString("yskm"));
            workFlowInfo.put("yskm", Util.null2String(rst.getString("yskm")));
        }
        return workFlowInfo;
    }

    /**
     * 根据角色名称获取人员id
     *
     * @param roleName
     * @return
     */
    public static String getPersonByRoleName(String roleName){
        RecordSet rs = new RecordSet();
        String resourceid = "";
        String sql = "select hrm.resourceid as resourceid from HrmRoles hr " +
                " join HrmRoleMembers hrm on hr.id = hrm.roleid where hr.rolesmark = ? and hrm.resourceid <> 1 ";
        log.info("sql:"+sql);
        rs.executeQuery(sql, roleName);
        while (rs.next()) {
            resourceid = Util.null2String(rs.getString("resourceid"));
        }
        return resourceid;
    }

    /**
     * 根据角色名称获取人员id
     *
     * @param departmentId
     * @return
     */
    public static String getCodeByDepartmentId(String departmentId){
        // 营销vop公司映射表表单id
        int marketingOfVopFormId = Integer.parseInt(com.customization.unionpay.market.util.PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_of_vop_form_id"));
        log.info("marketing_of_vop_form_id："+marketingOfVopFormId);
        String marketingOfVopFormTableName = FormDataUtils.getTableName(marketingOfVopFormId);
        log.info("获取营销vop公司映射表主表表名："+marketingOfVopFormTableName);
        RecordSet rs = new RecordSet();
        String code = "";
        String sql = "select jgbm from #{tableName} where gsmc = ? ";
        sql = sql.replace("#{tableName}", marketingOfVopFormTableName);
        log.info("sql："+sql);
        rs.executeQuery(sql, departmentId);
        while (rs.next()) {
            code = Util.null2String(rs.getString("jgbm"));
        }
        return code;
    }

    /**
     * 获取资金来源 编码
     * @param czfs
     * @return
     */
    public static String czfsName(String czfs){
        if("内部营销".equals(czfs)){
            return "0"; // 内部出资 "1000003";
        }else if("外部营销".equals(czfs)){
            return "1";  // 外部出资 "1000004";
        }else if("内外部联合营销".equals(czfs)){
            return "2";  // 内外部联合出资 "1000005";
        }else{
            return "";
        }
    }

    /**
     * 获取活动类型 编码
     * @param hdlx
     * @return
     */
    public static String hdlxName(String hdlx){
        if("立减".equals(hdlx)){
            return "0"; //"1000006";
        }else if("积分（普通）".equals(hdlx)){
            return "1"; //"1000037";
        }else if("奖励金".equals(hdlx)){
            return "2"; //"1000038";
        }else if("积分（消费送红包）".equals(hdlx)){
            return "3"; //"1000039";
        }else{
            return "";
        }
    }

    /**
     * 通用添加数据
     *
     * @param formId
     * @param formmodeId
     * @param user
     * @param maintablename
     * @param detailIndex
     * @param params
     * @param detailsParams
     */
    public static int addMainAndDetailsData(int formId, int formmodeId, User user, String maintablename, String detailIndex, JSONObject params, List<JSONObject> detailsParams) {

        if(params.size() <= 0){
            log.error("主表参数不能为空！");
            return -1;
        }
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);

        // 先调用内部方法新建一条数据，获取数据id
        int billid =  FormDataUtils.getBillId(maintablename, formmodeId, user.getUID(), user.getType());

        try {
            // 获取formbizid
            String formBizId = ShardingActionHelper.constructBizId(billid, formId);

            // 根据当前信息使用id修改新建数据
            StringBuilder updateMainSql = new StringBuilder("update ");

            updateMainSql.append(maintablename);
            updateMainSql.append(" set ");
            for (Object key : params.keySet()) {
                String keyStr = String.valueOf(key);
                updateMainSql.append(keyStr);
                updateMainSql.append("='");
                Object value = params.get(keyStr);
                if (value != null  && !"".equals(value)) {
                    updateMainSql.append(params.getString(keyStr));
                    updateMainSql.append("', ");
                }else {
                    updateMainSql.append("', ");
                }
            }

            updateMainSql.append(" form_biz_id = '");
            updateMainSql.append(formBizId);
            updateMainSql.append("' where id = ");
            updateMainSql.append(billid);
            log.info("updateMainSql：" + updateMainSql.toString());
            rst.executeUpdate(updateMainSql.toString());

            if(detailsParams != null && detailsParams.size() > 0){
                for (JSONObject detailsParam : detailsParams) {
                    if(detailsParam.size() > 0) {

                        StringBuilder addDetailsSql = new StringBuilder("insert into ");
                        addDetailsSql.append(maintablename);
                        addDetailsSql.append(detailIndex);

                        StringBuilder keySql = new StringBuilder(" (mainid,");
                        StringBuilder valueSql = new StringBuilder("('"+billid+"',");

                        for (Object detailsKey : detailsParam.keySet()) {
                            String detailsKeyStr = String.valueOf(detailsKey);
                            keySql.append(detailsKeyStr);
                            keySql.append(",");

                            Object value = detailsParam.get(detailsKeyStr);
                            if (value != null && !"".equals(value)) {
                                valueSql.append("'");
                                valueSql.append(detailsParam.getString(detailsKeyStr));
                                valueSql.append("',");
                            } else {
                                valueSql.append("'");
                                valueSql.append("',");
                            }
                        }
                        keySql.deleteCharAt(keySql.length() - 1);
                        valueSql.deleteCharAt(valueSql.length() - 1);

                        keySql.append(") ");
                        valueSql.append(")");

                        addDetailsSql.append(keySql);
                        addDetailsSql.append(" values");
                        addDetailsSql.append(valueSql);

                        log.info("addDetailsSql：" + addDetailsSql.toString());
                        rst.executeUpdate(addDetailsSql.toString());
                    }
                }
            }

            // 提交事务
            rst.commit();

            // 权限重构
            ModeRightInfo modeRightInfo = new ModeRightInfo();
            modeRightInfo.setNewRight(true);
            modeRightInfo.editModeDataShare(user.getUID(), formmodeId, billid);
            return billid;
        } catch (Exception e) {
            // 回滚
            rst.rollback();
            com.customization.unionpay.market.util.ClearFundButtonRelated.deleteByBillId(maintablename, billid);
            log.error("添加数据异常：" + e.getMessage());
            return -1;
        }
    }


    /**
     * 通用添加明细数据
     *
     * @param mainid
     * @param maintablename
     * @param detailIndex
     * @param detailsParams
     */
    public static boolean addDetailsData(String mainid, String maintablename, String detailIndex, List<JSONObject> detailsParams) {
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);

        try {

            StringBuilder addDetailsSql = new StringBuilder("insert into ");
            addDetailsSql.append(maintablename);
            addDetailsSql.append(detailIndex);

            StringBuilder keySql = new StringBuilder(" (mainid,");
            StringBuilder valueSql = new StringBuilder("('"+mainid+"',");

            if(detailsParams != null && detailsParams.size() > 0){
                for (JSONObject detailsParam : detailsParams) {
                    if(detailsParam.size() > 0) {
                        for (Object detailsKey : detailsParam.keySet()) {
                            String detailsKeyStr = String.valueOf(detailsKey);
                            keySql.append(detailsKeyStr);
                            keySql.append(",");

                            Object value = detailsParam.get(detailsKeyStr);
                            if (value != null && !"".equals(value)) {
                                valueSql.append("'");
                                valueSql.append(detailsParam.getString(detailsKeyStr));
                                valueSql.append("',");
                            } else {
                                valueSql.append("'");
                                valueSql.append("',");
                            }
                        }
                        keySql.deleteCharAt(keySql.length() - 1);
                        valueSql.deleteCharAt(valueSql.length() - 1);

                        keySql.append(") ");
                        valueSql.append(")");

                        addDetailsSql.append(keySql);
                        addDetailsSql.append(" values");
                        addDetailsSql.append(valueSql);

                        log.info("addDetailsSql：" + addDetailsSql.toString());
                        rst.executeUpdate(addDetailsSql.toString());
                    }
                }
            }

            // 提交事务
            rst.commit();

            return true;
        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("添加数据异常：" + e.getMessage());
            return false;
        }
    }


    public static String geJJSXIdByCode(String code) {
        code = code.replace(",","','");
        log.info("code:"+code);
        // 合同付款计划台账
        int htfkFormId = Integer.parseInt(com.customization.unionpay.market.util.PropUtils.BB_LOG.getPropValue("marketSubject", "htfk_form_id"));
        log.info("htfkFormId："+htfkFormId);
        String htfkFormIdFormTableName = getTableName(htfkFormId);
        log.info("合同付款计划台账主表表名："+htfkFormIdFormTableName);
        RecordSet rs = new RecordSet();
        String sql = "select jjsx from #{tableName} where id in ('"+code+"') ";
        sql = sql.replace("#{tableName}", htfkFormIdFormTableName);
        log.info("sql："+sql);
        rs.executeQuery(sql);
        StringBuilder jjsxs = new StringBuilder();
        while (rs.next()) {
            String jjsx = Util.null2String(rs.getString("jjsx"));
            if(!"".equals(jjsx)){
                jjsxs.append(jjsx);
                jjsxs.append(",");
            }
        }
        jjsxs = jjsxs.deleteCharAt(jjsxs.length() - 1);
        return jjsxs.toString();
    }

    /**
     * 推送提醒消息
     * @param userIdList           接收人id集合
     * @param linkUrl
     * @param linkMobileUrl
     * @throws Exception
     */
    public static void putWarningMessageInfo(Set<String> userIdList,String title,String context,String linkUrl,String linkMobileUrl) throws Exception {
        String messageid = PropUtils.BB_LOG.getPropValue("marketSubject", "expireMessageId");
        log.info("messageid:"+messageid);
        MessageType messageType = MessageType.newInstance(Integer.parseInt(messageid)); //消息来源（见文档第四点补充）
        MessageBean messageBean = null;
        try {
            messageBean = Util_Message.createMessage(messageType, userIdList, title, context, linkUrl, linkMobileUrl);
            messageBean.setCreater(1);//创建人id
            Util_Message.store(messageBean);
        } catch (Exception e) {
            log.error("推送消息失败："+e.getMessage());
            throw new Exception("推送消息失败："+e.getMessage());
        }
    }

    /**
     * 添加外部出资活动台账
     *
     * @param formId
     * @param formmodeId
     * @param maintablename
     * @param user
     * @param gs
     * @param bm
     * @param jbr
     * @param sqzy
     * @param htbm
     * @param htmc
     * @param projectCode
     * @param projectName
     * @param xmlxbm
     * @param xmlxmc
     * @param gysbm
     * @param gysmc
     * @param yxpthdsqm
     * @param kczje
     */
    public static void addExternalInfoBySth(int formId, int formmodeId, String maintablename, User user, String gs, String bm, String jbr, String sqzy, String htbm, String htmc, String projectCode, String projectName, String xmlxbm, String xmlxmc, String gysbm, String gysmc, String yxpthdsqm, String kczje) throws Exception {
        ClearingRefundServiceImpl clearingRefundService = new ClearingRefundServiceImpl();

        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);

        Integer bid = null;
        log.info("UID：" + user.getUID()+",Type："+user.getType());
        try {
            // 云闪付请求
            List<String> list = new ArrayList<>();
            list.add(yxpthdsqm);
            String resultStr = com.customization.unionpay.market.util.CloudFlashPaymentUtils.batchQueryByBudgetAuthCode(list);
            log.info("返回参数：" + resultStr);

            JSONObject resultJson = JSONObject.parseObject(resultStr);

            String errorMessage = resultJson.getString("errorMessage");
            if ("成功".equals(errorMessage)) {
                JSONArray data = resultJson.getJSONArray("data");
                log.info("解析data参数：" + data);
                if(data.size() > 0){
                    JSONObject single = data.getJSONObject(0);
                    // 活动名称             项目名称；
                    String projectNameYun = single.getString("projectName");
                    // 活动备注
                    // 活动管理人             申请人；
                    String applicantUserId = single.getString("applicantUserId") == null ? "营销系统管理员":single.getString("applicantUserId");
                    applicantUserId = FormDataUtils.getResourceIdByName(applicantUserId);
                    // 是否已结项   状态    5          下拉框【是/否】
                    String stat = "5".equals(single.getString("stat")) ? "0" : "1";
                    // 活动类型 = 项目业务类  0	立减活动  1	积分（普通） 2	消费送红包 3	激励金 4	新积分（补贴）  下拉框【立减/积分（普通）/奖励金/积分（消费送红包)
                    String projectBusiType = single.getString("projectBusiType");
                    String projectBusiTypeByTypeValue = clearingRefundService.getProjectBusiTypeByTypeValue(projectBusiType);
                    // 资金来源 = 授权码出资类型  1	内部 2	外部 3	内外联合
                    String contributionTypeChecked = single.getInteger("contributionTypeChecked") == null ? "" : String.valueOf((single.getInteger("contributionTypeChecked") - 1));
                    // 活动开始日期 = 项目开始日期
                    String projectStartDateChecked = single.getString("projectStartDateChecked");
                    // 活动结束日期 = 项目结束日期
                    String projectEndDateChecked = single.getString("projectEndDateChecked");

                    // TODO 同步资金账户类型
                    log.info("zjzhlx：" + single.getString("AcctType") );
                    Integer zjzhlx = single.getString("AcctType") == null ? 0 : (single.getInteger("AcctType")-1);
                    log.info("zjzhlx：" + zjzhlx);
                    // 先调用内部方法新建一条数据，获取数据id
                    bid = FormDataUtils.getBillId(maintablename, formmodeId, user.getUID(), user.getType());

                    // 获取formbizid
                    String formBizId = ShardingActionHelper.constructBizId(bid, formId);

                    // 根据当前信息使用id修改新建数据
                    StringBuilder updateSql = new StringBuilder("update ");
                    updateSql.append(maintablename);
                    updateSql.append(" set ");
                    if (yxpthdsqm != null && !"".equals(yxpthdsqm)) {
                        updateSql.append(" yxpthdsqm='");
                        updateSql.append(yxpthdsqm);
                        updateSql.append("', ");
                    }
                    if (gs != null && !"".equals(gs)) {
                        updateSql.append(" gs='");
                        updateSql.append(gs);
                        updateSql.append("', ");
                    }
                    if (bm != null && !"".equals(bm)) {
                        updateSql.append(" bm='");
                        updateSql.append(bm);
                        updateSql.append("', ");
                    }
                    if (jbr != null && !"".equals(jbr)) {
                        updateSql.append(" jbr='");
                        updateSql.append(jbr);
                        updateSql.append("', ");
                    }
                    if (sqzy != null && !"".equals(sqzy)) {
                        updateSql.append(" sqzy='");
                        updateSql.append(sqzy);
                        updateSql.append("', ");
                    }
                    if (htbm != null && !"".equals(htbm)) {
                        updateSql.append(" htbm='");
                        updateSql.append(htbm);
                        updateSql.append("', ");
                    }
                    if (htmc != null && !"".equals(htmc)) {
                        updateSql.append(" htmc='");
                        updateSql.append(htmc);
                        updateSql.append("', ");
                    }
                    if (projectCode != null && !"".equals(projectCode)) {
                        updateSql.append(" PROJECT_CODE='");
                        updateSql.append(projectCode);
                        updateSql.append("', ");
                    }
                    if (projectName != null && !"".equals(projectName)) {
                        updateSql.append(" PROJECT_NAME='");
                        updateSql.append(projectName);
                        updateSql.append("', ");
                    }
                    if (xmlxbm != null && !"".equals(xmlxbm)) {
                        updateSql.append(" xmlxbm='");
                        updateSql.append(xmlxbm);
                        updateSql.append("', ");
                    }
                    if (xmlxmc != null && !"".equals(xmlxmc)) {
                        updateSql.append(" xmlxmc='");
                        updateSql.append(xmlxmc);
                        updateSql.append("', ");
                    }
                    if (gysbm != null && !"".equals(gysbm)) {
                        updateSql.append(" gysbm='");
                        updateSql.append(gysbm);
                        updateSql.append("', ");
                    }
                    if (gysmc != null && !"".equals(gysmc)) {
                        updateSql.append(" gysmc='");
                        updateSql.append(gysmc);
                        updateSql.append("', ");
                    }
                    if (kczje != null && !"".equals(kczje)) {
                        updateSql.append(" kczje='");
                        updateSql.append(kczje);
                        updateSql.append("', ");
                    }
                    if (projectNameYun != null && !"".equals(projectNameYun)) {
                        updateSql.append(" ACT_NM='");
                        updateSql.append(projectNameYun);
                        updateSql.append("', ");
                    }
                    if (applicantUserId != null && !"".equals(applicantUserId)) {
                        updateSql.append(" hdglr='");
                        updateSql.append(applicantUserId);
                        updateSql.append("', ");
                    }
                    if (stat != null && !"".equals(stat)) {
                        updateSql.append(" sfyjx='");
                        updateSql.append(stat);
                        updateSql.append("', ");
                    }
                    if (projectBusiTypeByTypeValue != null && !"".equals(projectBusiTypeByTypeValue)) {
                        updateSql.append(" ACT_TP='");
                        updateSql.append(projectBusiTypeByTypeValue);
                        updateSql.append("', ");
                    }
                    if (contributionTypeChecked != null && !"".equals(contributionTypeChecked)) {
                        updateSql.append(" zjly='");
                        updateSql.append(contributionTypeChecked);
                        updateSql.append("', ");
                    }
                    if (projectStartDateChecked != null && !"".equals(projectStartDateChecked)) {
                        updateSql.append(" ACT_START_TM='");
                        updateSql.append(projectStartDateChecked);
                        updateSql.append("', ");
                    }
                    if (projectEndDateChecked != null && !"".equals(projectEndDateChecked)) {
                        updateSql.append(" ACT_END_TM='");
                        updateSql.append(projectEndDateChecked);
                        updateSql.append("', ");
                    }
                    if (zjzhlx != null && !"".equals(zjzhlx)) {
                        updateSql.append(" zjzhlx='");
                        updateSql.append(zjzhlx);
                        updateSql.append("', ");
                    }
                    updateSql.append( " form_biz_id = '");
                    updateSql.append(formBizId);
                    updateSql.append("' where id = ");
                    updateSql.append(bid);

                    log.info("添加中的修改sql：" + updateSql.toString());

                    rst.executeUpdate(updateSql.toString());
                    // 提交事务
                    rst.commit();

                    // 权限重构
                    ModeRightInfo modeRightInfo = new ModeRightInfo();
                    modeRightInfo.setNewRight(true);
                    modeRightInfo.editModeDataShare(user.getUID(), formmodeId, bid);
                }else {
                    log.error("云闪付根据授权码查询为空！");
                }
            } else {
                log.error("云闪付查询失败：" + resultJson.getString("errorCode") + "----" + resultJson.getString("errorMessage"));
            }
        } catch (Exception e) {
            // 回滚
            rst.rollback();
            if(bid != null) {
                com.customization.unionpay.market.util.ClearFundButtonRelated.deleteByBillId(maintablename, bid);
            }
            log.error("添加数据异常：" + e.getMessage());
            throw new Exception(e.getMessage());
        }
    }

    /**
     * 根据id修改清外部出资活动台账
     * @param maintablename
     * @param id
     * @param gs
     * @param bm
     * @param jbr
     * @param sqzy
     * @param htbm
     * @param htmc
     * @param projectName
     * @param xmlxbm
     * @param xmlxmc
     * @param gysbm
     * @param gysmc
     * @param yxpthdsqm
     * @param kczje
     */
    public static void updateInfoById(String maintablename, String id, String gs, String bm, String jbr, String sqzy, String htbm, String htmc, String projectName, String xmlxbm, String xmlxmc, String gysbm, String gysmc, String yxpthdsqm, String kczje) throws Exception {
        ClearingRefundServiceImpl clearingRefundService = new ClearingRefundServiceImpl();

        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);
        try {
            // 云闪付请求
            List<String> list = new ArrayList<>();
            list.add(yxpthdsqm);
            String resultStr = CloudFlashPaymentUtils.batchQueryByBudgetAuthCode(list);
            log.info("返回参数：" + resultStr);

            JSONObject resultJson = JSONObject.parseObject(resultStr);

            String errorMessage = resultJson.getString("errorMessage");
            if ("成功".equals(errorMessage)) {
                JSONArray data = resultJson.getJSONArray("data");
                log.info("解析data参数：" + data);

                JSONObject single = data.getJSONObject(0);
                // 活动名称             项目名称；
                String projectNameYun = single.getString("projectName");
                // 活动备注
                // 活动管理人             申请人；
                String applicantUserId = single.getString("applicantUserId");
                // 是否已结项   状态    5          下拉框【是/否】
                String stat = "5".equals(single.getString("stat")) ? "0" : "1";
                // 活动类型 = 项目业务类  0	立减活动  1	积分（普通） 2	消费送红包 3	激励金 4	新积分（补贴）  下拉框【立减/积分（普通）/奖励金/积分（消费送红包)
                String projectBusiType = single.getString("projectBusiType");
                String projectBusiTypeByTypeValue = clearingRefundService.getProjectBusiTypeByTypeValue(projectBusiType);
                // 资金来源 = 授权码出资类型  1	内部 2	外部 3	内外联合
                String contributionTypeChecked = single.getInteger("contributionTypeChecked") == null ? "" : String.valueOf((single.getInteger("contributionTypeChecked") - 1));
                // 活动开始日期 = 项目开始日期
                String projectStartDateChecked = single.getString("projectStartDateChecked");
                // 活动结束日期 = 项目结束日期
                String projectEndDateChecked = single.getString("projectEndDateChecked");

                // 根据当前信息使用id修改新建数据
                StringBuilder updateSql = new StringBuilder("update ");
                updateSql.append(maintablename);
                updateSql.append(" set  ");
                if (yxpthdsqm != null && !"".equals(yxpthdsqm)) {
                    updateSql.append(" yxpthdsqm='");
                    updateSql.append(yxpthdsqm);
                }
                if (gs != null && !"".equals(gs)){
                    updateSql.append("', ");
                    updateSql.append(" gs='");
                    updateSql.append(gs);
                }
                if (bm != null && !"".equals(bm)) {
                    updateSql.append("', ");
                    updateSql.append(" bm='");
                    updateSql.append(bm);
                }
                if (jbr != null && !"".equals(jbr)) {
                    updateSql.append("', ");
                    updateSql.append(" jbr='");
                    updateSql.append(jbr);
                }
                if (sqzy != null && !"".equals(sqzy)) {
                    updateSql.append("', ");
                    updateSql.append(" sqzy='");
                    updateSql.append(sqzy);
                }
                if (htbm != null && !"".equals(htbm)) {
                    updateSql.append("', ");
                    updateSql.append(" htbm='");
                    updateSql.append(htbm);
                }
                if (htmc != null && !"".equals(htmc)) {
                    updateSql.append("', ");
                    updateSql.append(" htmc='");
                    updateSql.append(htmc);
                }
                if (xmlxbm != null && !"".equals(xmlxbm)) {
                    updateSql.append("', ");
                    updateSql.append(" xmlxbm='");
                    updateSql.append(xmlxbm);
                }
                if (xmlxmc != null && !"".equals(xmlxmc)) {
                    updateSql.append("', ");
                    updateSql.append(" xmlxmc='");
                    updateSql.append(xmlxmc);
                }
                if (gysbm != null && !"".equals(gysbm)) {
                    updateSql.append("', ");
                    updateSql.append(" gysbm='");
                    updateSql.append(gysbm);
                }
                if (gysmc != null && !"".equals(gysmc)) {
                    updateSql.append("', ");
                    updateSql.append(" gysmc='");
                    updateSql.append(gysmc);
                }
                if (kczje != null && !"".equals(kczje)) {
                    updateSql.append("', ");
                    updateSql.append(" kczje='");
                    updateSql.append(kczje);
                }

                if (projectNameYun != null && !"".equals(projectNameYun)) {
                    updateSql.append("', ");
                    updateSql.append(" ACT_NM='");
                    updateSql.append(projectNameYun);
                }

                if (applicantUserId != null && !"".equals(applicantUserId)) {
                    updateSql.append("', ");
                    updateSql.append(" hdglr='");
                    updateSql.append(applicantUserId);
                }

                if (stat != null && !"".equals(stat)) {
                    updateSql.append("', ");
                    updateSql.append(" sfyjx='");
                    updateSql.append(stat);
                }

                if (projectBusiTypeByTypeValue != null && !"".equals(projectBusiTypeByTypeValue)) {
                    updateSql.append("', ");
                    updateSql.append(" ACT_TP='");
                    updateSql.append(projectBusiTypeByTypeValue);
                }

                if (contributionTypeChecked != null && !"".equals(contributionTypeChecked)) {
                    updateSql.append("', ");
                    updateSql.append(" zjly='");
                    updateSql.append(contributionTypeChecked);
                }

                if (projectStartDateChecked != null && !"".equals(projectStartDateChecked)) {
                    updateSql.append("', ");
                    updateSql.append(" hdksrq='");
                    updateSql.append(projectStartDateChecked);
                }

                if (projectEndDateChecked != null && !"".equals(projectEndDateChecked)) {
                    updateSql.append("', ");
                    updateSql.append(" hdjsrq='");
                    updateSql.append(projectEndDateChecked);
                }
                if (projectName != null && !"".equals(projectName)) {
                    updateSql.append("', ");
                    updateSql.append(" PROJECT_NAME='");
                    updateSql.append(projectName);
                }

                updateSql.append("' ");
                updateSql.append(" where id = ");
                updateSql.append(id);

                log.info("修改sql：" + updateSql.toString());
                rst.executeUpdate(updateSql.toString());
                // 提交事务
                rst.commit();
            } else {
                log.error("云闪付查询失败：" + resultJson.getString("errorCode") + "----" + resultJson.getString("errorMessage"));
            }
        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("修改数据异常：" + e.getMessage());
            throw new Exception(e.getMessage());
        }
    }


    /**
     * 根据唯一值查询外部出资活动台账
     *
     * @param maintablename
     * @param yxpthdsqm
     * @return
     */
    public static List<JSONObject> selectInfoByProjectCode(String maintablename, String yxpthdsqm) {
        RecordSet rst = new RecordSet();

        // 根据当前信息使用id修改新建数据
        String sql = "select id from #{tableName} where yxpthdsqm = ? ";
        sql = sql.replace("#{tableName}",maintablename);
        log.info("sql:"+sql);
        rst.executeQuery(sql,yxpthdsqm);

        List<JSONObject> list = new ArrayList<>();
        while (rst.next()) {
            JSONObject json = new JSONObject();
            json.put("id", Util.null2String(rst.getString("id")));
            list.add(json);
        }
        return list;
    }

    /**
     * 添加预算执行中间台账
     *
     * @param params
     */
    public static String addYuMiddleForm(int formId, int formmodeId, String maintablename, User user, JSONObject params) throws Exception {

        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);

        String lylc = params.getString("lylc");
        RecordSet rs = new RecordSet();

        // 根据当前信息使用id修改新建数据
        String sql = "select id from "+maintablename+" where lylc = '"+lylc+"' ";
        log.info("sql:"+sql);
        rs.executeQuery(sql);
        String id = "";
        while (rst.next()) {
            id = Util.null2String(rst.getString("id"));
        }
        if(("").equals(id)){
            Integer bid = null;
            log.info("UID：" + user.getUID()+",Type："+user.getType());
            try {
                // 先调用内部方法新建一条数据，获取数据id
                bid = FormDataUtils.getBillId(maintablename, formmodeId, user.getUID(), user.getType());

                id = String.valueOf(bid);

                // 获取formbizid
                String formBizId = ShardingActionHelper.constructBizId(bid, formId);

                // 根据当前信息使用id修改新建数据
                StringBuilder updateSql = new StringBuilder("update ");
                updateSql.append(maintablename);
                updateSql.append(" set ");

                for (String key : params.keySet()) {
                    Object keyObj = params.get(key);
                    if (keyObj != null && !"".equals(keyObj)) {
                        updateSql.append(" "+key+"='");
                        updateSql.append(params.getString(key));
                        updateSql.append("', ");
                    }
                }
                updateSql.append( " form_biz_id = '");
                updateSql.append(formBizId);
                updateSql.append("' where id = ");
                updateSql.append(bid);

                log.info("添加中的修改sql：" + updateSql.toString());

                rst.executeUpdate(updateSql.toString());
                // 提交事务
                rst.commit();

                // 权限重构
                ModeRightInfo modeRightInfo = new ModeRightInfo();
                modeRightInfo.setNewRight(true);
                modeRightInfo.editModeDataShare(user.getUID(), formmodeId, bid);
            } catch (Exception e) {
                // 回滚
                rst.rollback();
                if(bid != null) {
                    ClearFundButtonRelated.deleteByBillId(maintablename, bid);
                }
                log.error("添加数据异常：" + e.getMessage());
                throw new Exception(e.getMessage());
            }
        }else {
            // 根据当前信息使用id修改新建数据
            StringBuilder updateSql = new StringBuilder("update ");
            updateSql.append(maintablename);
            updateSql.append(" set ");

            for (String key : params.keySet()) {
                Object keyObj = params.get(key);
                if (keyObj != null && !"".equals(keyObj) && !"lylc".equals(keyObj)) {
                    updateSql.append(" "+key+"='");
                    updateSql.append(params.getString(key));
                    updateSql.append("', ");
                }
            }
            updateSql.append( " lylc = '");
            updateSql.append(lylc);
            updateSql.append("' where id = '");
            updateSql.append(id);
            updateSql.append("' ");
            log.info("添加中的修改sql：" + updateSql.toString());

            rst.executeUpdate(updateSql.toString());
            // 提交事务
            rst.commit();

        }

        return id;
    }

    /**
     * 查询事项台账是否核销
     * @param tableName
     * @param code
     * @param selectValueYes
     * @return
     */
    public static boolean selectSfhx(String tableName,String code,String selectValueYes){
        RecordSet rs = new RecordSet();
        boolean flag = false;
        try {
            StringBuilder sql = new StringBuilder("select id from  ");
            sql.append(tableName);
            sql.append(" where hdsfhx = '");
            sql.append(selectValueYes);
            sql.append("' and yxpthdsqm = '");
            sql.append(code);
            sql.append("' ");
            log.info("sql:"+sql);
            rs.executeQuery(sql.toString());
            while (rs.next()) {
                flag = true;
            }
        }catch (Exception e){
            log.error("查询异常：" + e.getMessage());
        }
        return flag;
    }

    /**
     * 查询营销活动事项台账信息
     * @param maintablename
     * @param id
     * @return
     * @throws Exception
     */
    public static  String selectMarketingActivityLedgerById(String maintablename,String id) {
        RecordSet rs = new RecordSet();
        String sqdh = null;
        String sql = "select sqdh from #{tableName} where id = ? ";
        sql = sql.replace("#{tableName}",maintablename);
        log.info("查询sql:"+sql);
        rs.executeQuery(sql,id);
        if (rs.next()) {
            while (rs.next()) {
                sqdh = Util.null2String(rs.getString("sqdh"));
            }
        }
        return sqdh;
    }
}
